<template>
  <layout-card
    class="data"
    style="height: 90%;background: #fff"
    headline="外部单位目录"
  >
    <template #action>
      <el-button type="primary" @click="handleCreate('add')"
      >新增类别</el-button
      >
    </template>
    <el-table
    row-key="id"
      v-loading="loading"
      size="large"
      :data="tabledata"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      :default-expand-all="true"
    >
      <el-table-column prop="unitCategory" label="单位类别" width="355" ></el-table-column>
      <el-table-column prop="creater" label="创建用户" width="355" align="center"></el-table-column>
      <el-table-column prop="creatTime" :formatter="timeFormat" label="创建时间" width="345" align="center"></el-table-column>
      <el-table-column prop="valid" label="是否有效" width="345" align="center">
        <template #default="{ row }">
          <el-text v-if="row.valid === 1">是</el-text>
          <el-text v-else>否</el-text>
        </template>
      </el-table-column>

      <el-table-column prop="action" label="操作" fixed="right" width="200" align="center">
        <template #default="{ row }">
          <!-- 自定义操作栏示例  -->
          <el-button class="link-btn" @click="addChildren(row)" link type="primary"
          >增加下级</el-button>
          <el-button class="link-btn" @click="handleEdit(row)" link type="primary"
          >编辑</el-button>
          <el-popconfirm
            title="是否删除?"
            confirmButtonText="确定"
            cancelButtonText="取消"
            @confirm="() => DeleteRow(row)"
          >
            <template #reference>
              <el-button class="link-btns" link type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

  </layout-card>
  <!-- 增加下级弹窗开始 -->
  <el-dialog v-model="addChildrenDialogVisible"  width="500" align-center  center style="border-radius: 12px">
    <div style="position: absolute;top: 18px;font-size: 16px;font-family: HarmonyOS_Sans_SC_Medium;color: #353A42;">{{addTilte}}</div>
    <div v-if="addTilte === '新建子类'" style="margin-left: 20px">
      <el-form-item>
        <!-- <el-text style="margin-left: 10px;">
          <template #default>
            <el-text v-if="formItem.layer === 1">一级类别：</el-text>
            <el-text v-if="formItem.layer === 2">二级类别：</el-text>
            <el-text v-if="formItem.layer === 3">三级类别：</el-text>
            <el-text v-if="formItem.layer === 4">四级类别：</el-text>
            <el-text v-if="formItem.layer === 5">五级类别：</el-text>
            <el-text v-if="formItem.layer === 6">六级类别：</el-text>
          </template>
        </el-text> -->
        <el-text style="margin-left: 10px;">{{formItem.selfName}}</el-text>
      </el-form-item>
    </div>
    <div style="margin-left: 20px">
      <el-form-item required label="类别名称">
        <el-input v-model="formItem.unitCategory" placeholder="请输入类别名称"></el-input>
      </el-form-item>
    </div>
    <div style="margin-left: 20px">
      <el-form-item required label="是否有效">
        <el-radio-group  v-model="formItem.valid">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addChildrenDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 设置弹窗结束 -->
</template>

<script lang="ts" setup>

  import { computed, onMounted, ref, reactive, onBeforeMount, nextTick } from "vue";
  import LayoutCard from "@/components/LayoutCard/index.vue";
  import {addCatalogue, editCatalogue, cataloguePageList, deleteCatalogue, getUserInfo} from "@/api/secure/catalogue"
  import {
    ElMessage,

  } from "element-plus";
  import { useStore } from "vuex";

  const loading = ref(false)
  const formItem = ref({
    valid: 0,
    unitCategory: '',
    fatherId: 0,
    selfName:''
  })

  // 新增弹窗
  const thresholdDialogVisible = ref(false);
  // 编辑弹窗
  const editDialogVisible = ref(false);
  // 增加子类弹窗
  const addChildrenDialogVisible = ref(false);
  const addTilte = ref(""); // 弹出框名称

  // 分页和数据展示参数
  const current = ref(1);
  const pageSize = ref(10);
  const total = ref(0);
  const tabledata = ref([]);
  const tableHeight = ref(window.innerHeight - 200)
  /**
   * @functionName 分页、查询、排序、删除功能
   * @author 杜思成
   * @date 2023-08-08 17:46:09
   * @version V1.0.0
   */
  const changeCurrent = (value: number) => {
    current.value = value;
  };
  const changePageSize = (size: number) => {
    pageSize.value = size;
  };
  const order = ref([
    {
      column: "state",
      method: "asc",
    },
    {
      column: "lastUpdateTime",
      method: "desc",
    },
  ]);

  const timeFormat = (row: any, column: any, cellValue: any) => {
    if (cellValue) {
      const date = new Date(cellValue);
      const year = date.getFullYear().toString();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    } else {
      return '-'
    }
  }
//一进页面数据要求
const data = {
  exterUnitCatalog:{},
  page:{
    page:0,
    size:10
  }
}
  /**
   * @functionName 获取数据
   */
  const getData = async () => {
    // loading.value = true
    cataloguePageList().then(res => {
      console.log(res);
        tabledata.value = res
        console.log(tabledata.value);
        loading.value = false
    }).catch(res => {
      console.log(res)
    })
  };

  /**
   * 保存
   */
  const save = () => {
    if (addTilte.value === '新建类别'||addTilte.value === '新建子类'){
      formItem.value.creatTime = timeFormat({},{},new Date())
      addCatalogue(formItem.value).then(res => {
        if (res){
          // 刷新数据
          getData();
          // 提示信息
          ElMessage({
            message: '新建成功',
            type: 'success',
          })
          // 关闭弹窗
          addChildrenDialogVisible.value = false
        }else {
          ElMessage({
            message: '新建失败',
            type: 'error',
          })
        }
      }).catch(res => {
        console.log(res)
      })
    }
    else if (addTilte.value === '编辑类别'){
      editCatalogue(formItem.value).then(res => {
        if (res){
          // 刷新数据
          getData();
          // 提示信息
          ElMessage({
            message: '编辑成功',
            type: 'success',
          })
          // 关闭弹窗
          addChildrenDialogVisible.value = false
        }else {
          ElMessage({
            message: '编辑失败',
            type: 'error',
          })
        }
        console.log(res)
      }).catch(res => {
        console.log(res)
      })
    }
  }
  onMounted(() => {
    getData();
  })

  const username = ref("")
  const getUser = (id:any) => {
    getUserInfo(id).then(res=>{
      username.value = res.data.userName
    }).catch(res=> {
      console.log(res)
    })
    return username.value
  }

  /**
   * @functionName 排序事件
   * @param {any} data 传入的某一列的列名和升降序
   * @author 彭庆楠
   * @date 2023-08-17 17:48:41
   * @version V1.0.0
   * @return
   */
  const sortChange = (data: any) => {
    const method = data.order === "ascending" ? "asc" : "desc";
    order.value[0].column = data.prop;
    order.value[0].method = method;
    getData();
  };

  const selectIds = (row:any) => {
    console.log(row)
  }

  // 删除
  const DeleteRow = (row: any) => {
    console.log(row)
    deleteCatalogue(row).then(res => {
      if (res){
        getData();
        ElMessage({
          message: '删除成功',
          type: 'success',
        })
      }else {
        ElMessage({
          message: '删除失败',
          type: 'error',
        })
      }

    }).catch(res => {
      console.log(res)
    })
  };

  /**
   * @functionName 新增、编辑弹出框
   * @param {any} val 判断打开那个弹窗
   */
  const handleCreate = (val: any) => {
    if (val === 'add'){
      formItem.value.valid = 0;
      formItem.value.unitCategory = '';
      formItem.value.fatherId = 0;
      addTilte.value = '新建类别'
    }
    if (val === "addChildren") {
      // 弹窗标题
      addTilte.value = "新建子类";
    }
    if (val === "edit") {
      // 弹窗标题
      addTilte.value = "编辑类别";
    }
    addChildrenDialogVisible.value =true;
  };
  // 增加下级
  const addChildren = async (row: any) => {
    formItem.value.valid = 0;
    formItem.value.unitCategory = '';
    formItem.value.fatherId = row.id;
    formItem.value.selfName = row.catalogueName;
    handleCreate('addChildren')
  };
  // 编辑
  const handleEdit = async (row: any) => {
    formItem.value = {...row}
    handleCreate('edit')
  };


</script>
<style lang="less" scoped>
  .form {
    /* .el-input { */

    /*  width: 150px; */

    /* } */
  }
  .data .card-content {
    height: 749px !important;
  }

  .el-breadcrumb{
    background: #fff;
  }

  .link-btn{
    color: #2F7DF1;
  }

  .link-btns{
    color:#F24A45;
  }

  ::v-deep .el-dialog__header {
    text-align: left !important;
  }

  /deep/.el-dialog__title {
    line-height: var(--el-dialog-font-line-height);
    font-size: var(--el-dialog-title-font-size);
    color: #2f59ac;
  }
</style>
